package studio.beamy.db.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import studio.beamy.db.profile.DBConnectionSetup;

public final class SessionFactoryUtil
{
	private static SessionFactoryUtil instance = null;

	private SessionFactoryUtil()
	{
	}

	public SessionFactory buildByHibernate(DBConnectionSetup ds)
	{
		try
		{
			final Configuration cfg = new Configuration();
			cfg.setProperty("hibernate.dialect", ds.getDialect());
			cfg.setProperty("hibernate.connection.driver_class", ds.getDbDriver());
			cfg.setProperty("hibernate.connection.url", ds.getDbUrl());
			cfg.setProperty("hibernate.connection.username", ds.getDbUser());
			cfg.setProperty("hibernate.connection.password", ds.getDbPwd());
			cfg.setProperty("hibernate.connection.pool_size", "5");
			cfg.setProperty("hibernate.connection.autocommit", "false");
			cfg.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.NoCacheProvider");
			// cfg.setProperty("hibernate.hbm2ddl.auto", "create-drop");
			cfg.setProperty("hibernate.hbm2ddl.auto", "update");
			cfg.setProperty("hibernate.show_sql", "true");
			cfg.setProperty("hibernate.format_sql", "true");
			cfg.setProperty("hibernate.use_sql_comments", "true");
			cfg.setProperty("hibernate.transaction.factory_class", "org.hibernate.transaction.JDBCTransactionFactory");
			cfg.setProperty("hibernate.current_session_context_class", "thread");
			cfg.setProperty("org.hibernate.flushMode", "COMMIT");
			cfg.setProperty("hibernate.generate_statistics", "true");
			// Hibernate entities
			for (Class<?> entity : ds.getAnnotatedClassList())
			{
				cfg.addAnnotatedClass(entity);
			}
			SessionFactory sessionFactory = cfg.buildSessionFactory();
			return sessionFactory;
			// org.springframework.orm.hibernate3.HibernateTransactionManager transactionManager = new
			// HibernateTransactionManager(sessionFactory);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public Connection buildByJDBC(DBConnectionSetup ds) throws Exception
	{
		Class.forName(ds.getDbDriver());
		Connection conn = DriverManager.getConnection(ds.getDbUrl(), ds.getDbUser(), ds.getDbPwd());
		return conn;
	}

	public static SessionFactoryUtil getInstance()
	{
		if (instance == null)
		{
			synchronized (SessionFactoryUtil.class)
			{
				if (instance == null)
				{
					instance = new SessionFactoryUtil();
				}
			}
		}
		return instance;
	}
}
